import mimetypes
import os
import platform

import xlrd
from openpyxl import load_workbook
from openpyxl.worksheet._read_only import ReadOnlyWorksheet
from utils.yamltool import BasePath


class _sheetTypeError(Exception):
	pass


if platform.system() == 'Linux':
	# 添加新的 MIME 类型
	mimetypes.add_type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx')


class ExcelReader:

	def __init__(self, file_path=None, sheet=None, title_line=True):
		if file_path is not None:
			self.file_path = os.path.join(BasePath, 'data', file_path)
			self.file_type, _ = mimetypes.guess_type(str(self.file_path))
		else:
			raise Exception("文件未找到!")
		self.sheet = 0 if sheet is None else sheet
		self.title_line = title_line
		self._data = list()

	@property
	def data(self):
		_sheet = None
		# 处理.xls文件
		if self.file_type == 'application/vnd.ms-excel':
			table = xlrd.open_workbook(self.file_path, formatting_info=True)
			if type(self.sheet) not in [int, str]:
				raise _sheetTypeError('Please pass in <type int> or <type str>, not {0}'.format(type(self.sheet)))
			# 通过索引处理sheet
			elif type(self.sheet) is int and self.sheet <= len(table.sheets()) - 1:
				_sheet = table.sheet_by_index(self.sheet)
			# 通过sheet名处理sheet
			elif type(self.sheet) is str and self.sheet in table.sheet_names():
				_sheet = table.sheet_by_name(self.sheet)
			else:
				raise Exception(f'{self.sheet}===表格没有数据或表格输入错误!')

			# 数据是否包含表头
			if self.title_line and type(_sheet) is xlrd.sheet.Sheet:
				title = _sheet.row_values(0)
				self._data = [dict(zip(title, _sheet.row_values(col))) for col in range(1, _sheet.nrows)]
			else:
				if _sheet is not None:
					self._data = [_sheet.row_values(col) for col in range(0, _sheet.nrows)]
		# 处理.xlsx文件
		elif self.file_type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
			table = load_workbook(self.file_path, read_only=True, data_only=True)
			if type(self.sheet) not in [int, str]:
				raise _sheetTypeError('Please pass in <type int> or <type str>, not {0}'.format(type(self.sheet)))
			# 通过索引处理sheet
			elif type(self.sheet) is int and self.sheet <= len(table.sheetnames) - 1:
				_sheet = table[table.sheetnames[self.sheet]]
			# 通过sheet名处理sheet
			elif type(self.sheet) is str and self.sheet in table.sheetnames:
				_sheet = table[self.sheet]
			else:
				raise Exception(f'{self.sheet}===表格没有数据或表格输入错误!')

			# 数据是否包含表头
			if self.title_line and type(_sheet) is ReadOnlyWorksheet:
				title = [cell.value for cell in _sheet[1]]
				self._data = [dict(zip(title, col)) for col in _sheet.iter_rows(min_row=2, values_only=True)]
			else:
				if _sheet is not None:
					self._data = [list(col) for col in _sheet.iter_rows(values_only=True)]
		else:
			raise Exception(f"不支持的文件格式: {self.file_type}")

		return self._data

# if __name__ == '__main__':
# 	vals = ExcelReader('自动化测试用例.xlsx').data
# 	for val in vals:
# 		print(val)
